<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>快照沙箱</title>
</head>
<body>
<script>
  class SnapshotSandbox {
    constructor() {
      this.proxy = window;
      this.modifyPropsMap = {}; //记录在window上的修改
      this.windowSnapshot = null;
      this.active();
    }

    active(){
      this.windowSnapshot = {};
      for (const prop in window) {
        if (window.hasOwnProperty(prop)) {
          this.windowSnapshot[prop] = window[prop]
        }
      }
      Object.keys(this.modifyPropsMap).forEach(p => {
        window[p] = this.modifyPropsMap[p];
      });
    }

    inactive(){
      for (const prop in window){
        if(window.hasOwnProperty(prop)){
          if (window[prop] !== this.windowSnapshot[prop]) {
            this.modifyPropsMap[prop] = window[prop];
            window[prop] = this.windowSnapshot[prop]
          }
        }
      }
    }
  }

  const sandbox = new SnapshotSandbox();

  ((window) => {
    window.a = 1;
    window.b = 2;
    console.log(window.a, window.b);

    sandbox.inactive();
    console.log(window.a, window.b);

    sandbox.active()
    console.log(window.a, window.b);

  })(sandbox.proxy); //sandbox.proxy就是window

  // 如果是多个子应用 就不能使用这种方式 而应该使用es6的proxy
</script>
</body>
</html>
